// pages/finance/profile/category/category.js
const financeCategory = require('../../../../utils/finance-category');
const dateUtil = require('../../../../utils/date');
const app = getApp();

Page({
  data: {
    categoryList: [],
    limit: 10,
    newCategoryName: '',
    newCategoryType: 'expense',
    newCategoryTypeIndex: 0,
    newCategoryTypeLabel: '支出',
    newCategoryIcon: '',
    newCategoryIconFile: null,
    newCategoryIconPreview: '',
    showEditId: '',
    editMode: false,
    editCategoryId: '',
    editCategoryType: 'expense',
    editCategoryIcon: '',
    editCategoryIconFile: null,
    editCategoryIconPreview: '',
    editCategoryName: '',
    submitting: false,
    typeOptions: [
      { label: '支出', value: 'expense' },
      { label: '收入', value: 'income' }
    ],
  },
  async onLoad() {
    await this.initData();
  },
  async initData() {
    wx.showLoading({ title: '加载中...' });
    try {
      const res = await financeCategory.categoryInit();
      const idx = this.data.typeOptions.findIndex(item => item.value === 'expense');
      this.setData({
        categoryList: res.list || [],
        limit: res.limit || 10,
        newCategoryName: '',
        newCategoryType: 'expense',
        newCategoryTypeIndex: idx,
        newCategoryTypeLabel: this.data.typeOptions[idx].label,
        newCategoryIcon: '',
        newCategoryIconFile: null,
        newCategoryIconPreview: '',
        editMode: false,
        editCategoryId: '',
        editCategoryType: 'expense',
        editCategoryIcon: '',
        editCategoryIconFile: null,
        editCategoryIconPreview: '',
        editCategoryName: '',
        submitting: false
      });
    } catch (e) {
      wx.showToast({ title: (e && e.data && e.data.msg) || '加载失败', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 600);
    } finally {
      wx.hideLoading();
    }
  },
  onNameInput(e) {
    const val = e.detail.value.slice(0, 4);
    this.setData({ newCategoryName: val });
  },
  onTypeChange(e) {
    const idx = e.detail.value;
    this.setData({
      newCategoryType: this.data.typeOptions[idx].value,
      newCategoryTypeIndex: idx,
      newCategoryTypeLabel: this.data.typeOptions[idx].label
    });
  },
  async onChooseIcon() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const filePath = res.tempFilePaths[0];
        wx.getFileSystemManager().getFileInfo({
          filePath,
          success: (info) => {
            if (info.size > 200 * 1024) {
              wx.showToast({ title: '图片不能超过200k', icon: 'none' });
              return;
            }
            this.setData({ newCategoryIcon: filePath, newCategoryIconPreview: filePath, newCategoryIconFile: filePath });
          },
          fail: () => {
            wx.showToast({ title: '图片读取失败', icon: 'none' });
          }
        });
      }
    });
  },
  async onSubmit() {
    if (this.data.submitting) return;
    const { newCategoryName, newCategoryType, newCategoryIcon, newCategoryIconFile, editMode, editCategoryId } = this.data;
    if (!newCategoryName) return wx.showToast({ title: '请输入分类名称', icon: 'none' });
    if (!newCategoryType) return wx.showToast({ title: '请选择类型', icon: 'none' });
    if (!newCategoryIcon) return wx.showToast({ title: '请选择图标', icon: 'none' });
    this.setData({ submitting: true });
    let iconBase64 = '';
    if (newCategoryIconFile) {
      try {
        const fileRes = wx.getFileSystemManager().readFileSync(newCategoryIconFile, 'base64');
        iconBase64 = fileRes;
      } catch (e) {
        wx.showToast({ title: '图片读取失败', icon: 'none' });
        this.setData({ submitting: false });
        return;
      }
    }
    try {
      if (editMode) {
        await financeCategory.categoryEdit({
          id: editCategoryId,
          name: newCategoryName,
          type: newCategoryType,
          iconBase64: iconBase64 || undefined
        });
        wx.showToast({ title: '编辑成功', icon: 'success' });
      } else {
        await financeCategory.categoryAdd({
          name: newCategoryName,
          type: newCategoryType,
          iconBase64
        });
        wx.showToast({ title: '新建成功', icon: 'success' });
      }
      await this.initData();
    } catch (e) {
      wx.showToast({ title: (e && e.data && e.data.msg) || '操作失败', icon: 'none' });
    } finally {
      this.setData({ submitting: false });
    }
  },
  onEditCategory(e) {
    const idx = e.currentTarget.dataset.index;
    const item = this.data.categoryList[idx];
    const typeIdx = this.data.typeOptions.findIndex(opt => opt.value === item.type);
    this.setData({
      editMode: true,
      editCategoryId: item.id,
      newCategoryName: item.name,
      newCategoryType: item.type,
      newCategoryTypeIndex: typeIdx,
      newCategoryTypeLabel: this.data.typeOptions[typeIdx].label,
      newCategoryIcon: item.icon,
      newCategoryIconPreview: item.icon,
      newCategoryIconFile: '',
    });
  },
  async onDeleteCategory(e) {
    const idx = e.currentTarget.dataset.index;
    const item = this.data.categoryList[idx];
    wx.showModal({
      title: '删除分类',
      content: '确定要删除该分类吗？这是不可逆操作，删除后该分类下已经记录的数据将无法查看。',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });
          try {
            await financeCategory.categoryDelete(item.id);
            wx.showToast({ title: '删除成功', icon: 'success' });
            await this.initData();
          } catch (e) {
            console.log(e)
            wx.showToast({ title: (e && e.data && e.data.msg) || '删除失败', icon: 'none' });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },
  onResetForm() {
    const idx = this.data.typeOptions.findIndex(item => item.value === 'expense');
    this.setData({
      editMode: false,
      editCategoryId: '',
      newCategoryName: '',
      newCategoryType: 'expense',
      newCategoryTypeIndex: idx,
      newCategoryTypeLabel: this.data.typeOptions[idx].label,
      newCategoryIcon: '',
      newCategoryIconPreview: '',
      newCategoryIconFile: '',
    });
  },
  // 设置默认
  async onSetDefaultCategory(e) {
    const idx = e.currentTarget.dataset.index;
    const item = this.data.categoryList[idx];
    wx.showLoading({ title: '设置中...' });
    try {
      await financeCategory.setDefaultFlag(item.id);
      wx.hideLoading();
      // 清空本地的账户缓存
      wx.removeStorageSync('categories');
      await this.initData();
    } catch (e) {
      console.log(e)
      wx.hideLoading();
      wx.showToast({ title: (e && e.data && e.data.msg) || '设置失败', icon: 'none' });
    }
  },
});